package com.maple.interceptor;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Component
public class LanguageInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取用户之前选择的语言，如果不存在则使用默认语言
        Locale selectedLocale = (Locale) request.getSession().getAttribute("sessionLocaleResolver.LOCALE");
        if (selectedLocale == null) {
            selectedLocale = Locale.getDefault();
            request.getSession().setAttribute("sessionLocaleResolver.LOCALE", selectedLocale);
        }

        // 设置Locale
        LocaleContextHolder.setLocale(selectedLocale);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // 在请求处理后清除Locale
        LocaleContextHolder.resetLocaleContext();
    }
}
